/**
 * @description 订单列表
 */
import style from './styles/List.less';
import classnames from "classnames";
import React from 'react';
const Fragment = React.Fragment;
import { Button, Toast, Dialog } from 'wd-mobile';
import ScrollReachEndContainer from "components/ScrollReachEndContainer";
import ShareOrPayLayer from "components/ShareOrPayLayer";
import wxShare from "commons/wxShare";

import { unconfirmed, finish, appeal } from "api_zhoujianyi/front/app/order/list";
import { _new } from "api_zhoujianyi/front/app/trade/list";
import { cancel } from "api_zhoujianyi/front/app/trade/purchase";
import { create_red_packet } from 'api_xukaiyu/app/share_redpacket';

import util from "commons/util";
let query = util.parseQueryString();

// img
import img_nolist from "./images/nolist.png";
import redPacket from "./images/redPacket.png";

// 订单状态枚举
const OrderStatus = {
    "WAIT_PAY": "支付处理中",
    "CANCELED": "已取消",
    "REFUNDED": "已退款",
    "WAIT_REFUND": "退款中"
}

class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            page: 1,
            // 数据
            data: [],
            hasload: false,
            scrollLoadText: "正在查询订单...",
        }

        // 是否正在加载数据
        this.loading = false;
    }
    componentDidMount() {
        this.toLoad();
        window.addEventListener('hashchange', this.reload, false);

    }

    componentWillUnmount() {
        window.removeEventListener('hashchange', this.reload, false);
    }

    reload = (target) => {
        location.reload();
        // let type = target.newURL.split('/').pop();
        // this.setState({
        //     page: 1,
        //     data:[]
        // }, () => {
        //     if (type == "unconfirmed") {
        //         this.unconfirmed();
        //     }
        //     if (type == "appeal") {
        //         this.appeal();
        //     }
        //     if (type == "finish") {
        //         this.finish();
        //     }
        //     if (type == "waitPay") {
        //         this.waitPay();
        //     }
        // })
    }
    render() {
        let { type } = this.props.match.params;
        return (
            <div className={style.container}>
                {type == 'unconfirmed' || type == 'appeal' ? <div className={style.navBar}>
                    <div className={classnames({ [style.acitve]: type == 'unconfirmed' })} onClick={() => { location.href = "./order.html#/List/unconfirmed" }}>未确认</div>
                    <div className={classnames({ [style.acitve]: type == 'appeal' })} onClick={() => { location.href = "./order.html#/List/appeal" }}>纠纷中</div>
                </div> : ''}
                <ScrollReachEndContainer threshold={2} showScrollLoadText={this.state.showScrollLoadText} loadText={this.state.scrollLoadText} className={classnames(style.main, "x-scroll-y")} onReachEnd={() => {
                    this.reachEnd();
                }}>
                    {
                        this.state.data.map((order, index) => {
                            return (
                                <div className={style.orderInfo} key={index} onClick={() => {
                                    location.href = `./order.html${this.props.match.params.type == "waitPay" ? util.joinQueryString({
                                        typeFrom: "waitPay",
                                        quantity: order.quantity
                                    }) : ""}#/Detail/${this.props.match.params.type == "waitPay" ? order.orderNos[0] : order.orderNo}`
                                }}>
                                    <div className={classnames(style.orderNo, "x-part")}>
                                        <span>
                                            {
                                                this.props.match.params.type == "waitPay" ?
                                                    `交易号：${order.tradeNo}` :
                                                    `订单号：${order.orderNo}`
                                            }
                                        </span>
                                    </div>
                                    <div className={classnames(style.orderInfoGoods, "x-part")}>
                                        <div className={style.orderInfoGoodsImg}>
                                            <div className={style.orderInfoGoodsImgContainer} style={order.goodsIcon ? { backgroundImage: `url(${order.goodsIcon})` } : null}></div>
                                        </div>
                                        { type != 'appeal' && order.userMark == 1 && this.props.match.params.type != "waitPay" && order.status != "WAIT_REFUND" && order.status != "WAIT_PAY" && order.status != "CANCELED" && order.status != "REFUNDED" ? (
                                            <span className={style.cardUseStatus}>已使用</span>
                                        ) : '' }
                                        <div className={style.orderInfoGoodsText}>
                                            <div className={style.orderInfoGoodsTitle}>
                                                <span>
                                                    {
                                                        this.props.match.params.type == "waitPay" ? order.goodsTypeName : order.goodsName
                                                    }
                                                </span>
                                            </div>
                                            <div className={style.orderTime}>
                                                <span>
                                                    下单时间：
                                                    {
                                                        this.props.match.params.type == "waitPay" ? order.gmtCreated : order.createTime
                                                    }
                                                </span>
                                            </div>
                                            {
                                                this.props.match.params.type == "waitPay" &&
                                                <div className={style.quantity}>
                                                    <span>数量：{order.quantity}</span>
                                                </div>
                                            }
                                            <div className={style.totalPrice}>
                                                <span className={style.totalPriceTitle}>合计：</span>
                                                <span className={style.totalPriceValue}>
                                                    ￥
                                                    {
                                                        this.props.match.params.type == "waitPay" ?
                                                            order.tradeAmount :
                                                            order.realPayAmount
                                                    }
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div className={classnames(style.orderInfoMore, "x-part")}>
                                        <div className={style.orderInfoMoreResult}>
                                            {this.props.match.params.type == "unconfirmed" ? <div className={style.shareRed} onClick={(e) => {
                                                e.stopPropagation();
                                                create_red_packet({ orderNo: order.orderNo }).then(data => {
                                                    let shareData = {};
                                                    let pathNameArr = location.pathname.split("/");
                                                    pathNameArr.pop();
                                                    shareData.link = location.origin + pathNameArr.join("/") + `/fightRedEnvelope.html#/GetCoupon/${data.data}`;
                                                    shareData.title = `送你一个大红包，最高5元！手慢无`;
                                                    shareData.desc = "天天拆红包，天天省点钱";
                                                    shareData.imgUrl = 'https://oss.weidai.com.cn/primKa8fks.png';
                                                    wxShare(shareData);
                                                    this.setState({
                                                        showShareOrPayLayer: true,
                                                        showDialog: false
                                                    })
                                                })
                                            }}><img src={redPacket} alt="" /> 分享领红包</div> : ""}
                                        </div>
                                        <div className={style.orderInfoMoreBtns}>
                                            {
                                                OrderStatus[order.status] && <div className={style.orderInfoStatus}>{OrderStatus[order.status]}</div>
                                            }
                                            {
                                                (this.props.match.params.type == "waitPay") && <Button className={classnames(style.orderInfoMoreBtn, style.continuePay)} onClick={(e) => {
                                                    e.stopPropagation();
                                                    location.href = `./goods.html?#/Pay/${order.tradeNo}`
                                                }}>继续支付</Button>
                                            }
                                            {
                                                (this.props.match.params.type == "waitPay") && <Button className={style.orderInfoMoreBtn} onClick={(e) => {
                                                    e.stopPropagation();
                                                    if (order.quantity > 1) {
                                                        Dialog.confirm(`本笔订单${order.quantity}个商品会同时取消，请确认是否取消 `, '取消订单', undefined, {
                                                            onOk: () => {
                                                                this.cancel(order.tradeNo, index);
                                                            },
                                                            onCancel: () => { },
                                                            buttons: { '确认': true, '放弃': false }
                                                        })
                                                    } else {
                                                        this.cancel(order.tradeNo, index);
                                                    }
                                                }}>取消支付</Button>
                                            }
                                            {
                                                (this.props.match.params.type == "appeal" || !!order.hasAppealRecord) && <Button className={style.orderInfoMoreBtn} onClick={(e) => {
                                                    e.stopPropagation();
                                                    location.href = `./order.html#/Disputes/${order.orderNo}`
                                                }}>查看进程</Button>
                                            }
                                            {
                                                (this.props.match.params.type != "waitPay" && order.status != "WAIT_REFUND" && order.status != "WAIT_PAY" && order.status != "CANCELED" && order.status != "REFUNDED") && <Button className={style.orderInfoMoreBtn} onClick={(e) => {
                                                    e.stopPropagation();
                                                    location.href = `./couponCode.html?orderNo=${order.orderNo}`
                                                }}>查看券码</Button>
                                            }
                                        </div>
                                    </div>
                                </div>
                            )
                        })
                    }
                    {
                        this.state.data.length <= 0 && !!this.state.hasload && <div className={style.nolist}>
                            <img src={img_nolist} alt="" />
                            <div>列表暂无信息</div>
                        </div>
                    }
                </ScrollReachEndContainer>
                <ShareOrPayLayer show={this.state.showShareOrPayLayer} onClick={() => {
                    this.setState({
                        showShareOrPayLayer: false
                    })
                }} />
            </div>
        )
    }

    // 取消订单
    cancel(tradeNo, index) {
        cancel({
            tradeNo: tradeNo
        }).then(res => {
            let tradeList = [...this.state.data];
            tradeList.splice(index, 1);
            this.setState({
                data: tradeList
            })
            Toast.info("取消成功");
        })
    }

    // 未确认
    unconfirmed() {
        unconfirmed({
            page: this.state.page
        }).then(res => {
            const newData = [...this.state.data, ...res.data.data];
            this.setState({
                data: newData,
                showScrollLoadText: newData.length > 0,
                scrollLoadText: res.data.data.length < 10 ? "没有更多订单" : "正在加载更多订单...",
                page: res.data.data.length < 1 ? this.state.page : this.state.page + 1,
                hasload: true
            })
            this.loading = false;
        })
    }

    // 已完成
    finish() {
        finish({
            page: this.state.page
        }).then(res => {
            const newData = [...this.state.data, ...res.data.data];
            this.setState({
                data: newData,
                showScrollLoadText: newData.length > 0,
                scrollLoadText: res.data.data.length < 10 ? "没有更多订单" : "正在加载更多订单...",
                page: res.data.data.length < 1 ? this.state.page : this.state.page + 1,
                hasload: true
            })
            this.loading = false;
        })
    }

    // 纠纷中
    appeal() {
        appeal({
            page: this.state.page
        }).then(res => {
            const newData = [...this.state.data, ...res.data.data];
            this.setState({
                data: newData,
                showScrollLoadText: newData.length > 0,
                scrollLoadText: res.data.data.length < 10 ? "没有更多订单" : "正在加载更多订单...",
                page: res.data.data.length < 1 ? this.state.page : this.state.page + 1,
                hasload: true
            })
            this.loading = false;
        })
    }

    // 待支付流水
    waitPay() {
        _new({
            page: this.state.page
        }).then(res => {
            const newData = [...this.state.data, ...res.data.data];
            this.setState({
                data: newData,
                showScrollLoadText: newData.length > 0,
                scrollLoadText: res.data.data.length < 10 ? "没有更多订单" : "正在加载更多订单...",
                page: res.data.data.length < 1 ? this.state.page : this.state.page + 1,
                hasload: true
            })
            this.loading = false;
        })
    }

    toLoad() {
        console.log('toLoad')
        if (this.props.match.params.type == "unconfirmed") {
            this.unconfirmed();
        }
        if (this.props.match.params.type == "appeal") {
            this.appeal();
        }
        if (this.props.match.params.type == "finish") {
            this.finish();
        }
        if (this.props.match.params.type == "waitPay") {
            this.waitPay();
        }
    }

    // 触底
    reachEnd() {
        console.log('reachEnd')
        if (!this.loading) {
            this.loading = true;
            this.toLoad();
        }
    }
}

export default App;